﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Security;

namespace DMS.Models
{
    public class UserIdentity : IIdentity, IPrincipal
    {
        private readonly FormsAuthenticationTicket _ticket;

        public UserIdentity(FormsAuthenticationTicket ticket)
        {
            _ticket = ticket;
        }

        public string AuthenticationType
        {
            get { return "User"; }
        }

        public bool IsAuthenticated
        {
            get { return true; }
        }

        public string Name
        {
            //get { return _ticket.Name; }
            get
            {
                if (this.AccountInfo != null)
                    return this.AccountInfo.Username;
                else
                    return _ticket.Name; ;
            }
        }

        public string UserData
        {
            get { return _ticket.UserData; }
        }

        public AccountObject AccountInfo
        {
            get
            {
                if (!string.IsNullOrEmpty(_ticket.UserData))
                {
                    var obj = JsonConvert.DeserializeObject<AccountObject>(_ticket.UserData);
                    return obj;
                }
                else
                {
                    return null;
                }
            }
        }

        public int UserId
        {
            get
            {
                if (this.AccountInfo != null)
                {
                    return this.AccountInfo.Id;
                }
                else
                {
                    return -1;
                }
            }
        }

        public int RoleId
        {
            get
            {
                if (this.AccountInfo != null)
                    return this.AccountInfo.Account_Role;
                else
                    return -1;
            }
        }

        public string UserName
        {
            get
            {
                if (this.AccountInfo != null)
                    return this.AccountInfo.Username;
                else
                    return "";
            }
        }

        public string Avatar
        {
            get
            {
                if (this.AccountInfo != null)
                    return this.AccountInfo.Avatar;
                else
                    return "";
            }
        }

        public bool IsInRole(string role)
        {
            return Roles.IsUserInRole(role);
        }

        public IIdentity Identity
        {
            get { return this; }
        }
    }
}